package com.pinyoumei.app.activity.integral;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.base.Request;
import com.pinyoumei.app.R;
import com.pinyoumei.app.activity.BaseActivity;
import com.pinyoumei.app.activity.WebViewActivity;
import com.pinyoumei.app.activity.ZBkOrderDetailActivity;
import com.pinyoumei.app.adapter.IntegralOrderAdapter;
import com.pinyoumei.app.adapter.ZBkOrderAdapter;
import com.pinyoumei.app.bean.BaseResultBean;
import com.pinyoumei.app.bean.ZBKOrderListBean;
import com.pinyoumei.app.fragment.SimpleCardFragment;
import com.pinyoumei.app.network.Constants;
import com.pinyoumei.app.utils.SPUtils;
import com.pinyoumei.app.utils.SignatureUtils;
import com.pinyoumei.app.utils.ToastUtils;
import com.pinyoumei.app.view.OnTabSelectListener;
import com.pinyoumei.app.view.SlidingTabLayout;
import com.pinyoumei.app.view.dialog.BaseDialog;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Administrator on 2021-06-30.
 * --------- 日期 ------- 维护人 ------------ 变更内容 --------
 * 2021-06-30        Administrator             新增Person类
 * 2021-06-30        Administrator             增加sex属性
 * 我的订单列表
 */
public class IntegralOrderListActivity extends BaseActivity implements View.OnClickListener {

    private final static String[] TITLE = {"全部","待发货","待收货","已完成"};
    private int order_type = 0;
    private int tab_type = 0;
    private int order_status = -1;
    private int page = 1;
    private SlidingTabLayout tl_5;
    private ViewPager vp;
    private MyPagerAdapter mAdapter;
    private ArrayList<Fragment> mFragments = new ArrayList<>();
    private IntegralOrderAdapter zBkOrderAdapter;
    private RecyclerView recyclerView;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_zbk_order_list);

        order_type = getIntent().getIntExtra("order_type",0);
        tab_type = getIntent().getIntExtra("tab_type",0);

        InitWidget();
        TextView zbk_title = findViewById(R.id.zbk_title);
        zbk_title.setText("积分订单");

        tl_5.setCurrentTab(tab_type);

        switch (tab_type) {
            case 0:
                order_status = -1;
                break;

            case 1:
                order_status = 1;
                break;


            case 2:
                order_status = 2;
                break;

            case 3:
                order_status = 3;
                break;
            default:
                break;
        }
          InitData();
    }

    private void InitWidget() {
        RelativeLayout relative_finish = findViewById(R.id.relative_finish);
        relative_finish.setOnClickListener(this);

        tl_5 = findViewById(R.id.tl_5);
        vp = findViewById(R.id.vp);

        for (int i = 0; i < TITLE.length; i++) {
            mFragments.add(SimpleCardFragment.getInstance(TITLE[i]));
        }
        mAdapter = new MyPagerAdapter(getSupportFragmentManager());

        vp.setAdapter(mAdapter);

        tl_5.setViewPager(vp);


        tl_5.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {

                switch (position) {
                	case 0:
                        order_status = -1;
                		break;

                    case 1:
                        order_status = 1;
                        break;


                    case 2:
                        order_status = 2;
                        break;

                    case 3:
                        order_status = 3;
                        break;
                	default:
                		break;
                }

                page = 1;
                InitData();

                for (int i = 0; i < tl_5.getTabCount(); i++) {
                    if (position == i) {
                        //选中的文字
                        tl_5.getTitleView(position).setTextSize(16f);
                        tl_5.getTitleView(i).setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
                    } else {
                        //未选中的文字，并且设置未选中时的不加粗
                        tl_5.getTitleView(i).setTextSize(14f);
                        tl_5.getTitleView(i).setTypeface(Typeface.DEFAULT);

                    }
                }
            }

            @Override
            public void onTabReselect(int position) {

            }
        });

        tl_5.getTitleView(0).setTextSize(16f);
        tl_5.getTitleView(0).setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
        tl_5.setCurrentTab(0);


        SmartRefreshLayout swipeRefreshLayout = findViewById(R.id.swipeRefreshLayout);
        swipeRefreshLayout.setEnableLoadMore(true);
        swipeRefreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                page++;
                LoadData();
                refreshLayout.finishLoadMore();
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                page=1;
                InitData();
                refreshLayout.finishRefresh();
            }
        });

        recyclerView = findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(new StaggeredGridLayoutManager(1,StaggeredGridLayoutManager.VERTICAL));
        zBkOrderAdapter = new IntegralOrderAdapter(R.layout.item_integral_order,null);
        recyclerView.setAdapter(zBkOrderAdapter);

        zBkOrderAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                switch (view.getId()) {
                	case R.id.bt_wl:

                        Express_Data(zBkOrderAdapter.getData().get(position).getId());

                		break;

                    case R.id.bt_xq:

                        Intent intent = new Intent(IntegralOrderListActivity.this, IntegralOrderDetailActivity.class);
                        intent.putExtra("order_id",zBkOrderAdapter.getData().get(position).getId());
                        intent.putExtra("order_type",order_type);
                        startActivity(intent);
                        break;

                    case R.id.bt_sure:
                        //取消订单
                        BaseDialog orderDialog = new BaseDialog(IntegralOrderListActivity.this, R.layout.dialog_tip);
                        orderDialog.setCancelable(false);
                        orderDialog.setCanceledOnTouchOutside(false);
                        orderDialog.show();
                        TextView tv_1 = orderDialog.findViewById(R.id.tv_1);
                        tv_1.setText("操作提示");
                        TextView tv_title = orderDialog.findViewById(R.id.tv_title);
                        tv_title.setText("请确认您是否已经收到对应的货物?");
                        Button bt_cancel = orderDialog.findViewById(R.id.bt_cancel);
                        bt_cancel.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                orderDialog.dismiss();
                            }
                        });

                        Button bt_sure = orderDialog.findViewById(R.id.bt_sure);

                        bt_sure.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                //确定
                                ConFirm_Data(zBkOrderAdapter.getData().get(position).getId());
                                orderDialog.dismiss();

                            }
                        });


                        break;
                	default:
                		break;
                }
            }
        });
    }

    private void InitData() {

        Map<String,Object> map = new HashMap<>();
        map.put("user_id", SPUtils.getAppUserId(IntegralOrderListActivity.this));
        map.put("order_type", "5");
        map.put("order_status", order_status);
        map.put("page", page);
        map.put("limit", 10);

        OkGo.<String>post( Constants.ZBK_ORDER_LIST)
                .params("user_id", SPUtils.getAppUserId(IntegralOrderListActivity.this))
                .params("order_type", "5")
                .params("order_status", order_status)
                .params("page", page)
                .params("limit", 10)
                .params("sign", SignatureUtils.createSignature(map, Constants.SIGN_SECRET))
                .execute(new StringCallback() {

                    @Override
                    public void onStart(Request<String, ? extends Request> request) {
                        super.onStart(request);
                        loadingDailog.show();
                    }



                    @Override
                    public void onSuccess(Response<String> response) {
                        setData(response);

                    }

                    private void setData(Response<String> response) {
                        loadingDailog.dismiss();

                        ZBKOrderListBean zbkOrderListBean = gson.fromJson(response.body(), ZBKOrderListBean.class);
                        if (zbkOrderListBean.getCode() >= 0 ){
                            zBkOrderAdapter.setNewData(zbkOrderListBean.getResult().getOrder_list());

                            //空页面
                            View notDataView = getLayoutInflater().inflate(R.layout.item_empty_view, (ViewGroup) recyclerView.getParent(), false);
                            zBkOrderAdapter.setEmptyView(notDataView);
                        }else{
                            ToastUtils.showShort(zbkOrderListBean.getMsg());
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        loadingDailog.dismiss();
                    }
                });




    }



    private void LoadData() {

        Map<String,Object> map = new HashMap<>();
        map.put("user_id", SPUtils.getAppUserId(IntegralOrderListActivity.this));
        map.put("order_type", "5");
        map.put("order_status", order_status);
        map.put("page", page);
        map.put("limit", 10);

        OkGo.<String>post( Constants.ZBK_ORDER_LIST)
                .params("user_id", SPUtils.getAppUserId(IntegralOrderListActivity.this))
                .params("order_type", "5")
                .params("order_status", order_status)
                .params("page", page)
                .params("limit", 10)
                .params("sign", SignatureUtils.createSignature(map, Constants.SIGN_SECRET))
                .execute(new StringCallback() {

                    @Override
                    public void onStart(Request<String, ? extends Request> request) {
                        super.onStart(request);
                        loadingDailog.show();
                    }



                    @Override
                    public void onSuccess(Response<String> response) {
                        setData(response);

                    }

                    private void setData(Response<String> response) {
                        loadingDailog.dismiss();

                        ZBKOrderListBean zbkOrderListBean = gson.fromJson(response.body(), ZBKOrderListBean.class);
                        if (zbkOrderListBean.getCode() >= 0 ){
                            zBkOrderAdapter.addData(zbkOrderListBean.getResult().getOrder_list());
                        }else{
                            ToastUtils.showShort(zbkOrderListBean.getMsg());
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        loadingDailog.dismiss();
                    }
                });




    }




    private void Express_Data(String order_id) {

        Map<String,Object> map = new HashMap<>();
        map.put("user_id", SPUtils.getAppUserId(IntegralOrderListActivity.this));
        map.put("order_id", order_id);
        map.put("order_type", order_type);


        OkGo.<String>post( Constants.ZBK_ORDER_EXPRESS_QUERY)
                .params("user_id", SPUtils.getAppUserId(IntegralOrderListActivity.this))
                .params("order_id", order_id)
                .params("order_type", order_type)
                .params("sign", SignatureUtils.createSignature(map, Constants.SIGN_SECRET))
                .execute(new StringCallback() {

                    @Override
                    public void onStart(Request<String, ? extends Request> request) {
                        super.onStart(request);
                        loadingDailog.show();
                    }



                    @Override
                    public void onSuccess(Response<String> response) {
                        setData(response);

                    }

                    private void setData(Response<String> response) {
                        loadingDailog.dismiss();

                        BaseResultBean baseResultBean = gson.fromJson(response.body(), BaseResultBean.class);
                        if (baseResultBean.getCode() >= 0 ){

//                            openBrowser(ZBkOrderListActivity.this,baseResultBean.getResult().getQuery_url());
                            Intent intent = new Intent(IntegralOrderListActivity.this, WebViewActivity.class);
                            intent.putExtra("url", baseResultBean.getResult().getQuery_url());
                            intent.putExtra("order_title", "物料详情");
                            startActivity(intent);
                        }else{
                            ToastUtils.showShort(baseResultBean.getMsg());
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        loadingDailog.dismiss();
                    }
                });




    }


    /**
     * 调用第三方浏览器打开
     *
     * @param context
     * @param url     要浏览的资源地址
     */
    public static void openBrowser(Context context, String url) {
        final Intent intent = new Intent();
        intent.setAction(Intent.ACTION_VIEW);
        intent.setData(Uri.parse(url));
        // 注意此处的判断intent.resolveActivity()可以返回显示该Intent的Activity对应的组件名
        // 官方解释 : Name of the component implementing an activity that can display the intent
        if (intent.resolveActivity(context.getPackageManager()) != null) {
            final ComponentName componentName = intent.resolveActivity(context.getPackageManager());
            // 打印Log   ComponentName到底是什么
            context.startActivity(Intent.createChooser(intent, "选择浏览器"));
        } else {
        }
    }


    private void ConFirm_Data(String order_id) {

        Map<String,Object> map = new HashMap<>();
        map.put("user_id", SPUtils.getAppUserId(IntegralOrderListActivity.this));
        map.put("order_id", order_id);
        map.put("order_type", order_type);


        OkGo.<String>post( Constants.ZBK_ORDER_EXPRESS_CONFIRM)
                .params("user_id", SPUtils.getAppUserId(IntegralOrderListActivity.this))
                .params("order_id", order_id)
                .params("order_type", order_type)
                .params("sign", SignatureUtils.createSignature(map, Constants.SIGN_SECRET))
                .execute(new StringCallback() {

                    @Override
                    public void onStart(Request<String, ? extends Request> request) {
                        super.onStart(request);
                        loadingDailog.show();
                    }



                    @Override
                    public void onSuccess(Response<String> response) {
                        setData(response);

                    }

                    private void setData(Response<String> response) {
                        loadingDailog.dismiss();

                        BaseResultBean baseResultBean = gson.fromJson(response.body(), BaseResultBean.class);
                        if (baseResultBean.getCode() >= 0 ){
                            page  = 1;
                            InitData();
                        }else{
                            ToastUtils.showShort(baseResultBean.getMsg());
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        loadingDailog.dismiss();
                    }
                });




    }



    private class MyPagerAdapter extends FragmentPagerAdapter {
        public MyPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public int getCount() {
            return mFragments.size();
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return TITLE[position];
        }

        @Override
        public Fragment getItem(int position) {
            return mFragments.get(position);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        	case R.id.relative_finish:
        		finish();
        		break;

        	default:
        		break;
        }
    }
}
